<?php
//占
class class_upfilemysql
{
	var $pxs = array();
	var $conn = 0;
	
	function __construct($conn = 0)
	{
		$this->pxs = is_array($GLOBALS['UPLOADIMGS_PX']) ? $GLOBALS['UPLOADIMGS_PX'] : array();
		$this->pxs[200] = 200;
		$this->conn = (int)$conn;
	}
	
	//---------------------------------------------------------------------------------------
	function del($id)
	{
		db_delete($GLOBALS['D_SI'], $id, 'id', $this->conn);
		
		foreach($this->pxs as $v)
		{
			db_delete($GLOBALS['D_SI'], $this->smallname($id, $v), 'id', $this->conn);
		}
	}
	//---------------------------------------------------------------------------------------
	function set($str)
	{
		$id = md5($str);
		$stat = db_insert($GLOBALS['D_SI'], $this->format($str, $id), $id, $this->conn);
		if($stat == false)
		{
			return db_stat() == 'same' ? $id : false;
		}
		
		return $id;
	}
	//---------------------------------------------------------------------------------------
	
	function get($id, $int = 0)
	{		
		if(strlen($id) == 32 && ctype_alnum($id))
		{
			if($int > 0)
				return $this->make($id, $int);
			

			$sql = "select * from {$GLOBALS['D_SI']} where id = '{$id}'";
			$row = db_find($sql, $this->conn);
			return empty($row) ? false : _bde($row['val']);
		}
		else
		{
			return false;
		}
	}
	//---------------------------------------------------------------------------------------
	protected function format($str,$id)
	{
		return "id='{$id}',val='"._ben($str)."'";
	}
	//---------------------------------------------------------------------------------------
	protected function smallname($id, $int)
	{
		return $id . '_' . $int;
	}
	//---------------------------------------------------------------------------------------
	protected function make($id, $int)
	{
		if(!isset($this->pxs[$int]))
		{
			_bug("upfilemysql:没有[{$int}]这个规格");
			return false;
		}
		
		$nid = $this->smallname($id, $int);

		$sql = "select * from {$GLOBALS['D_SI']} where id = '{$nid}'";
		$row = db_find($sql,$this->conn);
		
		if(empty($row))
		{
			$sql = "select * from {$GLOBALS['D_SI']} where id = '{$id}'";
			$tmp = db_find($sql,$this->conn);
						
			if(empty($tmp))
			{
				_bug("upfilemysql:没有[{$id}]这个原件");
				return false;
			}
			
			$old = _bde($tmp['val']);
			$img = NEW class_easyimage;
			$img->init($old);
			
			if(is_numeric($int))
			{
				$w = $int;
				$h = $int;
			}
			else
			{
				list($w, $h) = _split('x', $int);
			}
			
			$GLOBALS['UPLOADCUT'] ? $img->resizeCut($w, $h) : $img->resized($w, $h);
			
			$str = $img->str();
			db_insert($GLOBALS['D_SI'], $this->format($str, $nid), $nid, $this->conn);
		}
		else
		{
			$str = _bde($row['val']);
		}
		
		return $str;
	}

}